﻿using System;
using System.Collections.Generic;
using System.Linq;
using DMS.Business.Modules.Configuation;
using DMS.Business.Utility;
using DMS.Web.Common.Controls;
using DMS.Business.Modules.Organization;
using DMS.BaseClass;

namespace DMS.Web.Modules.SystemManagement.Organization
{
    public partial class ActorSettingForm : System.Web.UI.Page
    {
        private List<IConfigSetting> SettingForms
        {
            get
            {
                List<IConfigSetting> forms = new List<IConfigSetting>();

                forms.Add(this.cs_MailAlertSetting);
                forms.Add(this.cs_SMSAlertSetting);
                forms.Add(this.cs_BeginTimeSetting);
                forms.Add(this.cs_EndTimeSetting);

                return forms;
            }
        }

        #region 界面事件
        /// <summary>
        /// 界面加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.InitForms();
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            this.SaveForms();
        }
        #endregion

        #region 界面逻辑
        /// <summary>
        /// 初始化表单
        /// </summary>
        private void InitForms()
        {
            List<IConfigSetting> forms = this.SettingForms;
            foreach (IConfigSetting form in forms)
            {
                AuthenticationUser aUser = SystemContext.Current.LoginAuthUser;
                form.MemberID = aUser.ID.ToString();
                form.MemberType = ((int)aUser.ActorType).ToString();
                form.InitForm();
            }

            AuthenticationUser aUser1 = SystemContext.Current.LoginAuthUser;
            if (aUser1.ActorType==ActorTypes.SupplierAccount)
            {
                fs_delegate.Visible = false;
            }
            InitDelegateUser();
        }
        /// <summary>
        /// 保存表单
        /// </summary>
        private void SaveForms()
        {
            int errorCounter = 0;
            string lastCode = string.Empty;
            List<IConfigSetting> forms = this.SettingForms;
            foreach (IConfigSetting form in forms)
            {
                try
                {
                    form.Save();
                }
                catch (Exception ex)
                {
                    errorCounter++;
                    lastCode = LogHelper.LogException(ex);
                }
            }

            this.saveDelegateUser();

            if (errorCounter == 0)
            {
                ClientHelper.Instance.Alert("保存成功！");
                this.InitForms();
            }
            else if (errorCounter == this.SettingForms.Count)
            {
                string msg = string.Format("保存失败，请与管理员联系。\\r\\n错误码：{0}", lastCode);
                ClientHelper.Instance.Alert(msg);
            }
            else
            {
                string msg = string.Format("部分参数保存失败，请与管理员联系。\\r\\n错误码：{0}", lastCode);
                ClientHelper.Instance.Alert(msg);
            }
        }

        private void InitDelegateUser()
        {
            AuthenticationUser aUser = SystemContext.Current.LoginAuthUser;
            string MemberID = aUser.ID.ToString();

            string configId = "DelegateUser";
            string delegateBeginTimeId = "DelegateBeginTime";
            string delegateEndTimeId = "DelegateEndTime";
            
            SysConfig defaultConfig = null;
            SysConfig defaultDeleBeginTimeConfig = null;
            SysConfig defaultDeleEndTimeConfig = null;
            MemberConfig config = ConfigHelper.GetMemberConfig(MemberID, configId);
            MemberConfig delegateBeginTimeConfig = ConfigHelper.GetMemberConfig(MemberID, delegateBeginTimeId);
            MemberConfig delegateEndTimeConfig = ConfigHelper.GetMemberConfig(MemberID, delegateEndTimeId);
            if (config != null)
            {
                defaultConfig = config.Default;
                this.lblConfigTitle.Text = config.Name;
                this.hidDelegateUserId.Value = config.Value;
                if (!string.IsNullOrEmpty(config.Value))
                    this.delegateUserName.Text = UserHelper.GetUserByID(config.Value).Name;
                    //User delegateUser =  UserHelper.GetUserByID(new Guid(config.Value));
                    //this.delegateUserName.Text = delegateUser.Name + "【" + delegateUser.Dept.Name+ "】";
                else
                    this.delegateUserName.Text = "";
            }
            else
            {
                defaultConfig = ConfigHelper.GetSysConfigByID(configId);
                if (defaultConfig != null)
                {
                    this.lblConfigTitle.Text = defaultConfig.Name;
                    this.hidDelegateUserId.Value = defaultConfig.Value;
                    if (!string.IsNullOrEmpty(defaultConfig.Value))
                        this.delegateUserName.Text = UserHelper.GetUserByID(defaultConfig.Value).Name;
                }
                else
                {
                    ClientHelper.Instance.Alert("读取默认配置项时出错，请联系管理员。");
                }
            }

            if (delegateBeginTimeConfig != null && delegateEndTimeConfig != null)
            {
                if (!string.IsNullOrEmpty(delegateBeginTimeConfig.Value) && !string.IsNullOrEmpty(delegateEndTimeConfig.Value))
                {
                    this.tb_startDate.Text = delegateBeginTimeConfig.Value;
                    this.tb_endDate.Text = delegateEndTimeConfig.Value;
                }
                else
                {
                    this.tb_startDate.Text = "";
                    this.tb_endDate.Text = "";
                }
            }
            else
            {
                defaultDeleBeginTimeConfig = ConfigHelper.GetSysConfigByID(delegateBeginTimeId);
                defaultDeleEndTimeConfig = ConfigHelper.GetSysConfigByID(delegateEndTimeId);
                if (defaultDeleBeginTimeConfig != null && defaultDeleEndTimeConfig != null)
                {
                    if (!string.IsNullOrEmpty(defaultDeleBeginTimeConfig.Value) && !string.IsNullOrEmpty(defaultDeleEndTimeConfig.Value))
                    {
                        this.tb_startDate.Text = defaultDeleBeginTimeConfig.Value;
                        this.tb_endDate.Text = defaultDeleEndTimeConfig.Value;
                    }
                }
                else
                {
                    ClientHelper.Instance.Alert("读取默认配置项时出错，请联系管理员。");
                }
            }
        }

        private void saveDelegateUser() {
            AuthenticationUser aUser = SystemContext.Current.LoginAuthUser;
            string MemberID = aUser.ID.ToString();
            string MemberType = ((int)aUser.ActorType).ToString();
            string configId = "DelegateUser";
            string delegateBeginTimeId = "DelegateBeginTime";
            string delegateEndTimeId = "DelegateEndTime";

            List<MemberConfig> memberConfigs = ConfigHelper.GetMemberConfigs(MemberID);
            MemberConfig config = (from c in memberConfigs
                                   where c.ID == configId
                                   select c).ToList().DefaultIfEmpty(null).FirstOrDefault();
            MemberConfig delegateBeginTimeConfig = (from c in memberConfigs
                                                    where c.ID == delegateBeginTimeId
                                                    select c).ToList().DefaultIfEmpty(null).FirstOrDefault();
            MemberConfig delegateEndTimeConfig = (from c in memberConfigs
                                                  where c.ID == delegateEndTimeId
                                                  select c).ToList().DefaultIfEmpty(null).FirstOrDefault();
            Actor actor = null;
            ActorTypes actorType = (ActorTypes)Enum.Parse(typeof(ActorTypes), MemberType);

            if (config == null || delegateBeginTimeConfig == null || delegateEndTimeConfig == null) 
            {
                switch (actorType)
                {
                    case ActorTypes.Dept:
                        actor = UserHelper.GetDepartmentByID(MemberID) as Actor;
                        break;
                    case ActorTypes.Role:
                        actor = UserHelper.GetRoleByID(MemberID) as Actor;
                        break;
                    case ActorTypes.User:
                        actor = UserHelper.GetUserByID(MemberID) as Actor;
                        break;
                    case ActorTypes.SupplierAccount:
                        actor = SupplierHelper.GetAccountByID(MemberID) as Actor;
                        break;
                    case ActorTypes.Supplier:
                        actor = SupplierHelper.GetSupplierByID(MemberID) as Actor;
                        break;
                }
            }

            if (config == null)
            {
                //Actor actor = null;
                //ActorTypes actorType = (ActorTypes)Enum.Parse(typeof(ActorTypes), MemberType);
                SysConfig defaultConfig = ConfigHelper.GetSysConfigByID(configId);
                if (actor != null)
                {
                    config = new MemberConfig(actor, defaultConfig);
                }
                else
                {
                    LogicException ex = new LogicException("保存成员配置时，找不到成员实例，请检查成员类型或成员数据。");
                    LogHelper.LogException(ex);
                }
            }

            if (config != null)
            {
                config.Value = this.hidDelegateUserId.Value;
                config.Save();
            }

            if (delegateBeginTimeConfig == null || delegateEndTimeConfig == null)
            {
                SysConfig defaultDeleBeginTimeConfig = ConfigHelper.GetSysConfigByID(delegateBeginTimeId);
                SysConfig defaultDeleEndTimeConfig = ConfigHelper.GetSysConfigByID(delegateEndTimeId);
                if (actor != null)
                {
                    delegateBeginTimeConfig = new MemberConfig(actor, defaultDeleBeginTimeConfig);
                    delegateEndTimeConfig = new MemberConfig(actor, defaultDeleEndTimeConfig);
                }
                else
                {
                    LogicException ex = new LogicException("保存成员配置时，找不到成员实例，请检查成员类型或成员数据。");
                    LogHelper.LogException(ex);
                }
            }

            if (delegateBeginTimeConfig != null && delegateEndTimeConfig != null)
            {
                delegateBeginTimeConfig.Value = this.tb_startDate.Text;
                delegateEndTimeConfig.Value = this.tb_endDate.Text;
                
                delegateBeginTimeConfig.Save();
                delegateEndTimeConfig.Save();
            }
        }
        #endregion
    }
}